<?php

namespace App\Http\Controllers\Alipay;
use App\Enums\SmsTempEnum;
use App\Jobs\SendChangeOrderMessage;
use App\Jobs\SendSmsMessageJob;
use App\Models\MemberLegal;
use App\Services\AlipayMiniAppService;
use App\Services\NotarizeService;
use App\Services\RedisLock;
use App\Services\RedisService;
use App\Models\Express;
use App\Models\Goods;
use App\Models\GoodsCustomRent;
use App\Models\GoodsHuabei;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Models\MemberAddress;
use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLog;
use App\Models\OrderRefund;
use App\Models\OrderRemark;
use App\Models\OrderReturn;
use App\Models\OtherOrder;
use App\Models\OtherOrderAllocate;
use App\Models\ShopSms;
use App\Models\ShopTrans;
use App\Models\ShopUser;
use App\Models\UnicomOrder;
use App\Services\AlipayMessageService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\LogisticsService;
use App\Services\OrderService;
use App\Services\RadarService;
use App\Services\UnicomService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     * 确认订单页面接口
     */
    public function confirmOrder(Request $request){
        $goods_id = $request->input('goods_id');
        $setmeal_id = $request->input('setmeal_id');
        $spec_id = $request->input('spec_id');
        $amount = $request->input('amount');
        $huabei_stages = $request->input('huabei_stages');
        $insurance = isset($request['insurance'])?$request['insurance']:'7';
        $pact_type = isset($request['pact_type'])?$request['pact_type']:'2';

        if(empty($goods_id) || empty($setmeal_id) || empty($spec_id) || empty($amount)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品参数');
        }
        //商品
        $goods = Goods::checkGoodsStatus($goods_id);
        if(empty($goods)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在');
        }
        //套餐
        $setmeal = GoodsSetmeal::CheckGoodsSetmeal($goods_id,$setmeal_id);
        if(empty($setmeal)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '套餐不存在');
        }
        //租期
        $spec = GoodsSpec::CheckGoodsSpec($goods_id,$setmeal_id,$spec_id);
        if(empty($spec)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期信息不存在');
        }
        $lease_time = GetRentTime($setmeal['lease_set'],$setmeal['start_date'],$spec['lease_time']);
        $data['lease_time'] = $lease_time['begin_date'].'-'.$lease_time['end_date'];//租赁时间

        $insurance_money = '0.00';
        if($insurance){
            $order_data['is_insurance_choose'] = $insurance;
            $insurance_money = GoodsService::getGoodsInsurance($insurance);
        }

        $data['buyout_price'] =  '';
        if($pact_type == GoodsService::GOODS_BUYOUT_NO){ //可买断
            $data['is_buy_out'] =1;
            $data['buyout_price'] = sprintf("%.2f",$setmeal['buyout_price'] * $amount);
            $data['buyout_price'] = $data['buyout_price']>0?$data['buyout_price']:0;
        }
        if($pact_type == '2'){
            $data['is_buy_out'] =0;
            $data['buyout_price'] = '0.00';
        }

        if($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月
            $data['total_rent'] = sprintf("%.2f",$spec['lease_time']*$spec['day_price']*$amount+$insurance_money-$data['buyout_price']);//总租金
            $data['every_rent']   = sprintf("%.2f", $data['total_rent']/$spec['lease_time']);//每期租金
            $data['total_num'] = $spec['lease_time'];//总租期
            $data['first_rent'] = sprintf("%.2f", $data['every_rent']+$insurance_money);
        }elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天
            $data['total_num']  = DayToPeriods($spec['lease_time']);//总租期
            $data['total_rent'] = sprintf("%.2f",$spec['lease_time'] * $spec['day_price']*$amount+$insurance_money-$data['buyout_price']);//总租金
            if($spec['lease_time'] <= 30){
                $data['first_rent'] = $data['total_rent'];
            }else{
                $data['first_rent'] = sprintf("%.2f",$data['total_rent']/$data['total_num']+$insurance_money);
            }
        }elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
            $custom = GoodsCustomRent::where([['goods_id',$goods_id],['setmeal_id',$setmeal_id],['spec_id',$spec_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->select('which_period','lease_days','lease_price','day_price','withhold_cycle')->get();
            $custom = $custom ? $custom->toArray() : [];
            $data['total_rent'] = sprintf("%.2f",array_sum(array_column($custom,'day_price'))*$amount+$insurance_money-$data['buyout_price']);//总租金
            if(empty($custom)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期信息不存在');
            }else{
                $data['total_num'] = count($custom);//总租期
                $data['first_rent'] = sprintf("%.2f", $data['total_rent']/$data['total_num']+$insurance_money);//首期租金
            }
        }
        $data['last_rent'] = sprintf("%.2f",$data['total_rent']-$data['first_rent']);
        $data['last_term'] = $data['total_num']-1;
        $data['pay_type'] = $pact_type;
        $data['pact_type'] = GoodsService::getGoodsPactName($pact_type);
        if(!empty($huabei_stages)){
            $data['pay_type'] = OrderLease::LEASE_PAY_TYPE_HUABEI;
            $data['total_num'] = $huabei_stages;
            $huabei_fee_bear = GoodsHuabei::getHuabeiFeeBear($goods_id,$setmeal_id,$spec_id,$huabei_stages);
            if($huabei_fee_bear == GoodsService::GOODS_HUABEI_FEE_USER){//用户承担  计算手续费
                $fee_ratio = GoodsHuabei::HUABEI_USER_FEE_BEAR_LIST[$huabei_stages];
                $huabei_total = $data['total_rent'] + $data['total_rent'] * $fee_ratio * 0.01;
                $data['huabei_every_rent'] = round($huabei_total/$huabei_stages,2);
                $data['stages_fee'] = sprintf("%.2f",$data['total_rent'] * $fee_ratio * 0.01);
            }else{
                $data['huabei_every_rent'] = sprintf("%.2f",$data['total_rent']/$huabei_stages);
                $data['stages_fee'] = 0;
            }
        }
        $data['goods_name']  = $goods['title'];
        $data['goods_img'] = $goods['imgurl'];
        $data['amount'] = $amount;
        $data['setmeal_title'] = $setmeal['title'];
        $data['foregift'] = sprintf("%.2f",$setmeal['foregift']*$amount);
        $data['convey_type'] = '寄出'.GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$goods['convey_type1']].'--退货'.GoodsService::GOODS_RETURN_CONVEY_TYPE_NAME_LIST[$goods['convey_type2']];


        $data['price'] = sprintf("%.2f",$setmeal['price'] * $amount);
        $data['contract_type'] = $goods['contract_type'];
        $data['sign_num'] = $goods['sign_num'];
        $member_id = $goods['member_id'];
        if(!empty($member_id)){
            $data['emergency_contact_status'] = ShopUser::where('member_id',$member_id)->value('emergency_contact');
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    /**
     * 获取订单租期详情
     */
    public function getOrderLeaseTerm(Request $request){
        $goods_id = $request->input('goods_id');
        $setmeal_id = $request->input('setmeal_id');
        $spec_id = $request->input('spec_id');
        $amount = $request->input('amount');
        $pact_type = $request->input('pact_type')??'2';
        if(empty($goods_id) || empty($setmeal_id) || empty($spec_id) || empty($amount)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少商品参数');
        }
        //商品
        $goods = Goods::checkGoodsStatus($goods_id);
        if(empty($goods)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在');
        }
        //套餐
        $setmeal = GoodsSetmeal::CheckGoodsSetmeal($goods_id,$setmeal_id);
        if(empty($setmeal)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '套餐不存在');
        }
        //租期
        $spec = GoodsSpec::CheckGoodsSpec($goods_id,$setmeal_id,$spec_id);
        if(empty($spec)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期信息不存在');
        }
        $lease_time = GetRentTime($setmeal['lease_set'],$setmeal['start_date'],$spec['lease_time']);
        $data['goods_name'] = $goods['title'];
        $data['setmeal_name'] = $setmeal['title'];
        $data['goods_price'] = sprintf("%01.2f",$setmeal['price']*$amount);
        $data['lease_set'] = $setmeal['lease_set'];
        $data['withhold_cycle'] = 30;
        $data['lease_time'] = $lease_time['begin_date'].'-'.$lease_time['end_date'];//租赁时间
        $start_date = $setmeal['start_date']*3600*24;
        if($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月
            if($pact_type=='1'){
                $data['total_rent'] = sprintf("%01.2f",$spec['lease_time']*$spec['day_price']*$amount-$setmeal['buyout_price']*$amount);//总租金
                $data['first_rent'] = sprintf("%01.2f",$data['total_rent']/$spec['lease_time']*$amount);//首期租金
            }else{
                $data['total_rent'] = sprintf("%01.2f",$spec['lease_time']*$spec['day_price']*$amount);//总租金
                $data['first_rent'] = sprintf("%01.2f",$data['total_rent']/$spec['lease_time']*$amount);//首期租金
            }
            $data['total_num'] = $spec['lease_time'];//总租期
            for ($i=0;$i<$spec['lease_time'];$i++){
                $which_period = $i+1;
                $begin = time() + $start_date;
                $begin_time = date('Y.m.d',strtotime("+$which_period months",$begin));
                $end_time = date("Y.m.d",strtotime("+1 months", strtotime(str_replace('.','-',$begin_time))));
                $data['order_lease'][$i]['which_period'] = '第'.$which_period.'期';
                $data['order_lease'][$i]['lease_term'] = $begin_time.'-'.$end_time;
                $data['order_lease'][$i]['lease_price']  = sprintf("%01.2f",$data['first_rent']);
            }
        }elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天
            $data['total_num']  = DayToPeriods($spec['lease_time']);//总租期
            if($pact_type=='1'){
                $data['total_rent'] = sprintf("%01.2f",$spec['lease_time'] * $spec['day_price']*$amount-$setmeal['buyout_price']*$amount);//总租金
                $data['lease_price'] = sprintf("%01.2f",$data['total_rent']/$data['total_num']);//首期租金
            }else{
                $data['total_rent'] = sprintf("%01.2f",$spec['lease_time'] * $spec['day_price']*$amount);//总租金
                $data['lease_price'] = sprintf("%01.2f",$data['total_rent']/$data['total_num']);//首期租金
            }
            if($spec['lease_time'] <= 30){
                $data['first_rent'] = $data['total_rent'];
                $which_period = $spec['lease_time'];
                $begin = time() + $start_date;
                $begin_time = date('Y.m.d',strtotime("+$which_period day",$begin));
                $end_time = date("Y.m.d",strtotime("+30 day", strtotime(str_replace('.','-',$begin_time))));
                $data['order_lease'][0]['which_period'] = '第1期';
                $data['order_lease'][0]['lease_term'] = $begin_time.'-'.$end_time;
                $data['order_lease'][0]['lease_price']  = sprintf("%01.2f", $data['lease_price']);
            }else{
                $data['first_rent'] = sprintf("%01.2f", $data['lease_price']*$amount);
                for ($i=0;$i<floor($spec['lease_time']/30);$i++){
                    // if($i+1 == floor($spec['lease_time']/30)){
                    //     $rent_day = $spec['lease_time']%30;
                    //     $which_period = $i*30+$rent_day;
                    // }else{
                    //     $which_period = ($i)*30;
                    //     $rent_day = 30;
                    // }
                    // $rent_period = $i+1;
                    // $begin = time() + $start_date;
                    // $begin_time = date('Y.m.d',strtotime("+$which_period day",$begin));
                    // $end_time = date("Y.m.d",strtotime("+$rent_day day", strtotime(str_replace('.','-',$begin_time))));
                    // $data['order_lease'][$i]['which_period'] = '第'.$rent_period.'期';
                    // $data['order_lease'][$i]['lease_term'] = $begin_time.'-'.$end_time;
                    // $data['order_lease'][$i]['lease_price']  = sprintf("%01.2f",$spec['day_price']*$rent_day*$amount);
                    $rent_period = $i+1;
                    $begin_time = date("Y.m.d",strtotime("+$i month", time() + $start_date));
                    $end_time = date("Y.m.d",strtotime("+1 month", strtotime(str_replace('.','-',$begin_time))));
                    $end_time = $end_time>$lease_time['end_date'] ? $lease_time['end_date']:$end_time;
                    $data['order_lease'][$i]['which_period'] = '第'.$rent_period.'期';
                    $data['order_lease'][$i]['lease_term'] = $begin_time.'-'.$end_time;
                    $data['order_lease'][$i]['lease_price']  = sprintf("%01.2f", $data['lease_price']*$amount);
                }
            }

        }elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
            $custom = GoodsCustomRent::where([['goods_id',$goods_id],['setmeal_id',$setmeal_id],['spec_id',$spec_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->select('which_period','lease_days','lease_price','day_price','withhold_cycle')->get();
            $custom = $custom ? $custom->toArray() : [];
            if(empty($custom)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期信息不存在');
            }else{
                $data['total_num'] = count($custom);//总租期
                $data['first_rent'] = sprintf("%01.2f",$custom[0]['day_price']*$amount);//首期租金
                $data['withhold_cycle'] = $custom[0]['withhold_cycle'];
                foreach ($custom as $k=>$v){
                    $lease_days = $v['lease_days'];
                    $base = $k * $lease_days;
                    $begin = time() + $start_date;
                    $begin_time = date('Y.m.d',strtotime("+$base day",$begin));
                    $end_time = date("Y.m.d",strtotime("+$lease_days day", strtotime(str_replace('.','-',$begin_time))));
                    $data['order_lease'][$k]['which_period'] = '第'.$v['which_period'].'期';
                    $data['order_lease'][$k]['lease_term'] = $begin_time.'-'.$end_time;
                    $data['order_lease'][$k]['lease_price'] = sprintf("%01.2f",$v['day_price']*$amount);
                }
            }
            $data['total_rent'] = sprintf("%01.2f",array_sum(array_column($custom,'day_price'))*$amount);//总租金
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }


    /**
     * 生成订单
     */
    public function makeOrder(Request $request)
    {
        $data = $request->input();
        $miniId = AlipayMiniAppService::getInstance()->getMiniId();
        $user = $this->member;
        $data['status'] = OrderService::ORDER_STATUS_NOT_PAY;
        $res = Order::createOrder($miniId, $data, $user);
        if ($res['status'] == CommonService::HTTP_CODE_SUCCESS) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '订单创建成功', $res['data']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }
    }

    /**
     * 唤起预授权
     */
    public function createPreAuth(Request $request)
    {
        $order_id = $request->input('order_id');
        if ($order_id) {
            $order = Order::where('id', $order_id)
                ->select('id', 'mini_id', 'trade_no', 'rent_total', 'rights_auth_no', 'foregift', 'month_total',
                    'amount', 'uid', 'status', 'address', 'mobile', 'realname')
                ->first();
            $order = $order ? $order->toArray() : [];
            if (!empty($order)) {

                // 所属平台
                $miniId = $order['mini_id'];

                // if($order['status'] > OrderService::ORDER_STATUS_NOT_PAY){
                if ($order['rights_auth_no']) {
                    $data['orderStr'] = '';
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '预授权已签约', $data);
                }

                $memberLegal = MemberLegal::where('uid', $order['uid'])->select('is_legal', 'id')->first();
                if ($memberLegal && $memberLegal['is_legal'] == 0) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单状态不可签约');
                }
                $order_goods = OrderGoods::from('sp_order_goods_2 as og')->select('og.goods_title', 'og.setmeal_foregift', 'og.pact_type', 'c.rent_category')
                    ->leftjoin('sp_goods_2 as g', 'g.id', 'og.goods_id')
                    ->leftjoin('sp_category as c', 'c.id', 'g.category_id')
                    ->where('og.order_id', $order_id)
                    ->first();
                $order_goods = $order_goods ? $order_goods->toArray() : [];
                if (!empty($order_goods)) {
                    $data['rentPeriod'] = $order['month_total'] * 30;
                    $data['rentAmount'] = $order['rent_total'];
                    $data['deliveryAddress'] = $order['address'];
                    $data['deliveryMobile'] = $order['mobile'];
                    $data['deliveryName'] = $order['realname'];

                    $data['orderNo'] = $order['trade_no'];
                    $data['goodsTitle'] = $order_goods['goods_title'];
                    $data['preAmount'] = $order['foregift'];

                    $data['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_XXZ_URL_PRE_AUTH;
                    $data['zmCategory'] = $order_goods['rent_category'];
                    $data['month_total'] = $order['month_total'];
                    $ali_res = AlipayService::alipayPreLicensing($miniId, $data);
                    if ($ali_res['status']) {
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '创建成功', $ali_res['data']);
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, $ali_res['message']);
                    }
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少订单号');
        }
    }




    /**
     * 花呗支付
     */
    public function createHuabei(Request $request){
        $order_id = $request->input('order_id');
        if($order_id){
            $order = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_goods_2 as g','g.order_id','o.id')
                ->where('o.id',$order_id)
                ->select('o.id', 'o.mini_id', 'o.trade_no', 'o.rent_total', 'o.status', 'o.amount', 'o.uid',
                    'g.goods_id', 'g.setmeal_id', 'g.spec_id', 'g.lease_set', 'g.lease_time', 'g.goods_title', 'o.flow_id', 'o.sign_status')
                ->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                if($order['status'] == OrderService::ORDER_STATUS_NOT_PAY){//未支付  正常下单流程
                    if(!empty($order['huabei_stages']) && $order['huabei_stages'] > 0 ){
                        $huabei = GoodsHuabei::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']]])
                            ->select('rent_total','three_bear','three_fee','six_bear','six_fee','twelve_bear','twelve_fee')->first();
                        $huabei = $huabei ? $huabei->toArray() : [];
                        if(!empty($huabei)){
                            $hbfee_bear = GoodsHuabei::getHuabeiFeeBear($order['goods_id'],$order['setmeal_id'],$order['spec_id'],$order['huabei_stages']);
                            if($hbfee_bear == 1){
                                $hbfeebear = 100;
                            }else{
                                $hbfeebear = 0;
                            }

                            $miniId = $order['mini_id'];

                            $pay_data['orderNo'] = $order['trade_no'];
                            $pay_data['totalAmount'] = $order['rent_total'];
                            $pay_data['goodsTitle']  = $order['goods_title'];
                            $pay_data['buyerId'] = $this->member['user_id'];
                            $pay_data['huabeiStages'] = $order['huabei_stages'];
                            $pay_data['hbFeeBear'] = $hbfeebear;
                            $pay_data['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_HUABEI_PAY;
                            $ali_res = AlipayService::alipayHuabei($miniId, $pay_data);
                            if($ali_res['status']){
                                $data['trade_no'] = $ali_res['data']['trade_no'];
                                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'创建成功',$data);
                            } else {
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败',$ali_res);
                            }
                        }else{
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '花呗分期信息不存在');
                        }
                    }else{
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该订单未选择花呗支付');
                    }
                }elseif($order['status'] == OrderService::ORDER_STATUS_PAY_SUCCESS){ //已支付  返回合同签署状态及信息
                    $data['sign_status'] = $order['sign_status'];
                    $data['flow_id'] = $order['flow_id'];
                    $data['esign_user_id'] = MemberOther::where('id',$order['uid'])->value('esign_user_id');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功',$data);
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单状态错误');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少订单号');
        }
    }


    /**
     * 创建合同
     */
    public function createContract(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->leftjoin('sp_order_credit as c','c.order_id','o.id')
                ->leftjoin('sp_member_2 as u','o.uid','u.id')
                ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
                ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
                ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
                ->select(
                    'o.id', 'o.mini_id', 'o.trade_no', 'o.begin_time', 'o.zulinbao_order_id', 'o.end_time', 'o.pact_url_3', 'o.uid', 'o.seller_id', 'o.is_insurance_choose',
                    'o.flow_id', 'o.mobile', 'o.user_email', 'o.sign_num', 'o.address', 'o.rent_total', 'o.month_total', 'o.amount', 'o.realname', 'o.rent_total',
                    'o.foregift', 'o.status', 'o.prov', 'o.city', 'o.area', 'o.sign_status', 'o.is_rent_choose'
                    , 'c.platformLoanNo', 'o.create_time'
                    , 'u.ant_user_id', 'u.mobile as user_mobile', 'u.id as x_user_id', 'u.cert_name', 'u.user_id', 'u.cert_no', 'u.esign_user_id'
                    , 'u.idcard_front', 'u.idcard_back', 'og.id as order_goods_id ', 'og.pact_type', 'og.is_buy_out', 'og.goods_title', 'og.setmeal_title',
                    'og.lease_set', 'og.setmeal_price', 'og.setmeal_foregift',
                    'og.goods_id', 'og.setmeal_id', 'og.id as order_goods_id', 'og.spec_id', 'og.lease_price', 'og.lease_time', 'og.website_price', 'og.start_date'
                    , 'su.mechanism', 'su.faname', 'su.shopname', 'su.contact_tel', 'su.company', 'su.company_area', 'su.companyid', 'su.id as shop_user_id'
                    , 'su.ant_user_id as mer_ant_id', 'o.sign_no', 'su.esign_seal_id'
                    , 'g.new_grade')
                ->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){

                Order::where('id',$order_id)->update(['sign_status'=>EsignService::ESIGN_STATUS_SIGNING]);

                if(!empty($order['flow_id'])){
                    $signStatus = AntchainAtoService::querySignFlow($order['sign_no']);
                    if(isset($signStatus['status']) && $signStatus['status'] =='DRAFT'){
                        $data['flowId'] = $order['flow_id'];
                        $data['signerId'] = $order['esign_user_id'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'草稿！重新发起签署',$data);
                    }
                    if(isset($signStatus['status']) && $signStatus['status']=='SIGNING'){
                        $data['flowId'] = $order['flow_id'];
                        $data['signerId'] = $order['esign_user_id'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'合同签署中，请勿重复发起',$data);
                    }
                    if(isset($signStatus['status']) && $signStatus['status'] == 'FINISH'){
                        $res= $signStatus;
                        $docList=json_decode($res['docList'],true);
                        if($res['resultCode']=='OK'&&$res['status']=='FINISH'&&empty($order['pact_url'])){
                            $fileUrl = $docList[0]['downloadUrl'];
                            $fileName = $res['flowId'].".pdf";
                            $file = file_get_contents($fileUrl);
                            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

                            file_put_contents($path,$file);
                            $uploud_res = AlipayService::upload($fileName,$path);
                            if($uploud_res['status']){
                                if(file_exists($path)){
                                    unlink($path);
                                }
                            }
                            $order_data['sign_no']=$res['signNo'];
                            $order_data['pact_url'] = $fileName;
                            $order_data['sign_status']  = EsignService::ESIGN_STATUS_FINISH;
                            Order::where('id',$order['id'])->update($order_data);
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署已完成');
                        }
                    }
                }
//                if(empty($order['esign_user_id'])){
//                    $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
//                    $data1 = $result['data'];
//                    if(!empty($data1['accountId'])){
//                        $esign_user_id = $data1['accountId'];
//                        MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
//                    }else{
//                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
//                    }
//                }else{
//                    $user_mobile = !empty($order['user_mobile'])?$order['user_mobile']:$order['mobile'];
//                    $esign_user_id = EsignService::updateAccounts($order['esign_user_id'],$user_mobile,$order['cert_name']);
//                }
//
//                $order['pact_type'] = GoodsService::getGoodsPactName($order['pact_type']);
//                $order['isBuyout'] = $order['is_buy_out'];
//                $order['is_buy_out'] = GoodsService::getGoodsBuyoutName($order['is_buy_out']);
//
//                if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月
//                    $first_rent = GoodsSpec::where([['id',$order['spec_id']],['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']]])->value('lease_price');
//                    if(!empty($first_rent)){//首期租金
//                        $order['first_rent'] = sprintf("%.2f",$first_rent * $order['amount']);
//                    }else{
//                        $order['first_rent'] = 0;
//                    }
//                }elseif ($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天
//                    $goods_spec = GoodsSpec::where([['id',$order['spec_id']],['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']]])->select('lease_price','lease_time')->first();
//                    $goods_spec = $goods_spec ? $goods_spec->toArray() : [];
//                    if($goods_spec['lease_time'] <= 30){
//                        $order['first_rent'] = $order['rent_total'];
//                    }else{
//                        $order['first_rent'] = sprintf("%.2f",(($goods_spec['lease_price']*30)*100)/100*$order['amount']);
//                    }
//                }elseif ($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
//                    $custom = GoodsCustomRent::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->select('which_period','lease_days','lease_price','withhold_cycle')->get();
//                    $custom = $custom ? $custom->toArray() : [];
//                    if(!empty($custom)){
//                        $order['first_rent'] = sprintf("%.2f",$custom[0]['lease_price'] * $order['amount']);//首期租金
//                    }
//                }
//                $shop_user = ShopUser::where('member_id',$order['seller_id'])->select('mechanism','company','faname','esign_shop_id','company_area','agreement','contact_tel','esign_seal_id','companyid')->first();
//                $shop_user = $shop_user ? $shop_user->toArray() : [];
                //创建合同
                //     $result = EsignService::createFlowOneStepShopThree($order,$shop_user,$esign_user_id);
                $result = AntchainAtoService::submitBehindSignFlow($order);
                if(!empty($result['resultCode']) &&$result['resultCode']=='OK'){
                    $flowId = $result['flowId'];
                    $signNo= $result['signNo'];
                    $esign_user_id = $result['accountId'];
                    MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
                    $signInfo=json_decode($result['signInfo'],true);
                    $res = Order::where('id',$order_id)->update(['flow_id'=>$flowId,'sign_no'=>$signNo,'sign_url'=>$signInfo['shortUrl'],'sign_status'=>EsignService::ESIGN_STATUS_SIGNING]);
                    if($res){
                        $data['flowId'] = $flowId;
                        $data['signerId'] = $esign_user_id;
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'合同发起成功',$data);
                    }else{
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署信息记录失败');
                    }
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同创建失败，请联系客服');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }
    /**
     * 获取订单数量
     */
    public function getOrderCount()
    {
        $user = $this->member;
        $miniId = AlipayMiniAppService::getInstance()->getMiniId();

        $order_count = Order::alipayOrderCount($miniId, $user['id']);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $order_count);
    }


    /**
     * C端 订单列表
     */
    public function orderList(Request $request)
    {
        $request_data = $request->input();
        $miniId = AlipayMiniAppService::getInstance()->getMiniId();

        $user = $this->member;
        $order_list = Order::alipayOrderList($miniId, $request_data, $user['id']);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $order_list);
    }

    /**
     * 订单详情
     */
    public function orderInfo(Request $request)
    {
        $order_id = $request->input('order_id');
        if (empty($order_id)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
        $user = $this->member;
        $order_res = Order::alipayOrderInfo($order_id, $user['id']);
        if ($order_res['status'] == CommonService::HTTP_CODE_SUCCESS) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $order_res['data']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
        }
    }

    /**
     * 账单详情
     */
    public function getOrderLease(Request $request)
    {
        $order_id = $request->input('order_id');
        if (empty($order_id)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
        $user = $this->member;
        $order_res = OrderLease::alipayOrderLease($order_id, $user['id']);
        if ($order_res['status'] == CommonService::HTTP_CODE_SUCCESS) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $order_res['data']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
        }
    }

    /**
     * 未支付取消订单
     */
    public function orderCancel(Request $request){
        $order_id = $request->input('order_id');
        $status=Order::where('id',$order_id)->value('status');
        if($status==OrderService::ORDER_STATUS_PAY_SUCCESS){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品打包中，请联系客服15372089067');
        }


        $name= $request->input('name');
        if(!empty($order_id)&&$status<OrderService::ORDER_STATUS_PAY_SUCCESS){
            $user = $this->member;
            $order_res = Order::noPayOrderCancel($order_id,$user['id'],false);
            if($order_res['status'] == CommonService::HTTP_CODE_SUCCESS){
                SendChangeOrderMessage::dispatch($order_id,AlipayMessageService::KX_SHOPPING);
                if(!empty($name)){
                    $add = [
                        'uid'=>23,
                        'username'=>'用户取消订单',
                        'create_time'=>time(),
                        'remark'=>$name,
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add);
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'取消成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     *  获取申请退款页面信息
     */
    public function getOrderRefundData(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $user = $this->member;
            $order = Order::from('sp_order_2 as o')->leftjoin('sp_order_goods_2 as g','o.id','g.order_id')
                ->where([['o.id',$order_id],['o.uid',$user['id']]])
                ->wherein('o.status',[OrderService::ORDER_STATUS_PAY_SUCCESS,OrderService::ORDER_STATUS_SIGN_NOTRISK,OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_REFUSE])
                ->select('g.order_id','g.goods_title','g.imgurl','g.setmeal_title','o.mobile','o.amount','o.begin_time','o.end_time')->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                $order['paid_rent'] = OrderLease::where([['order_id',$order['order_id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('paid_rent');
                $order['lease_time'] = date("Y.m.d",strtotime($order['begin_time'])).'-'.date("Y.m.d",strtotime($order['end_time']));
                $order['refund_type_list'] = OrderRefund::ORDER_REFUND_TYPE_LIST;
                $order['refund_reason_list'] = OrderRefund::ORDER_REFUND_ONLY_REASON_LIST;
                unset($order['begin_time']);
                unset($order['end_time']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或该订单状态不支持退款操作');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 已支付待发货订单申请退款
     */
    public function applyOrderRefund(Request $request){
        $order_id = $request->input('order_id');
        $user_mobile = $request->input('user_mobile');
        $refund_amount = $request->input('refund_amount');
        $refund_reason = $request->input('refund_reason');
        $refund_desc = $request->input('refund_desc');
        $refund_image = $request->input('refund_image');
        $redis = new RedisService();
        $lock = RedisLock::lock($redis, 'orderIdRefund'.$order_id);
        if(!$lock){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '系统繁忙，请稍后再试');
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品打包中，请联系客服15372089067');
        if(!empty($order_id)){
            if(empty($refund_amount) || empty($refund_reason)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退款金额、退款原因不能为空');
            }
            $paid_ren = OrderLease::where([['order_id',$order_id],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('paid_rent');
            if($paid_ren < $refund_amount){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退款金额不能大于已支付金额');
            }


            $user = $this->member;
            $order = Order::from('sp_order_2 as o')->where([['o.id',$order_id],['o.uid',$user['id']]])
                ->where('o.status',OrderService::ORDER_STATUS_PAY_SUCCESS)
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->lockForUpdate()
                ->select('o.id as order_id', 'o.mini_id', 'o.pay_type','o.status','o.rent_total','o.rights_auth_no','o.trade_no',
                    'o.alipay_trade_no','o.seller_id','o.month_total','o.uid','o.realname','o.order_from','o.financing_type',
                    'o.is_skip','s.shop_balance','og.goods_title','o.payer_user_id','og.goods_id','o.sign_no',
                    'o.settlement_status','o.pay_time','s.refund_check','s.shopname','o.flow_id','o.rights_auth_no','o.alipay_trade_no')->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                $order_lease = OrderLease::where([['status',OrderLease::ORDER_LEASE_STATUS_PAID],['order_id',$order['order_id']]])
                    ->select('id','order_id','which_period','rent','paid_rent','settle_type','out_order_no','alipay_trade_no','status')->get();
                $order_lease = obToArray($order_lease);
                $deduct_amount = 0;
                $lease_id_arr=[];
                if(!empty($order_lease)){
                    foreach ($order_lease as $k=>$v){
                        $order_trans = ShopTrans::getOrderRefundTrans($order,$v);
                        if(!empty($order_trans) && isset($order_trans['settle_amount'])){
                            $deduct_amount += $order_trans['settle_amount'];
                        }
                        $lease_id_arr[]=$v['id'];
                    }
                }
                $data['order_id'] = $order_id;
                $data['user_mobile'] = $user_mobile;
                $data['refund_amount'] = $refund_amount;
                $data['deduct_amount'] = $deduct_amount;
                $data['paid_total_rent'] = array_sum(array_column($order_lease,'paid_rent'));
                $data['refund_type'] = OrderRefund::ORDER_REFUND_TYPE_ONLY_REFUND;
                $data['refund_reason'] = $refund_reason;
                $data['refund_desc'] = $refund_desc;
                $data['refund_image'] = $refund_image;
                $data['refund_order_status'] = $order['status'];
                $data['refund_status'] = OrderRefund::ORDER_REFUND_NOCHECK;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['update_time'] = date('Y-m-d H:i:s');
                if(OrderRefund::where('order_id',$order_id)->wherein('refund_status',[OrderRefund::ORDER_REFUND_NOCHECK,OrderRefund::ORDER_REFUND_SHOP_CHECKED,OrderRefund::ORDER_REFUND_SHOP_REFUSE,OrderRefund::ORDER_REFUND_ADMIN_REFUSE,OrderRefund::ORDER_REFUND_CANCEL])->count() > 0){
                    DB::beginTransaction();
                    $add_re = OrderRefund::where('order_id',$order_id)->update($data);
                }else{
                    DB::beginTransaction();
                    $add_re = OrderRefund::insert($data);
                }
                $res = Order::where([['id',$order_id],['uid',$user['id']]])->update(['status'=>OrderService::ORDER_STATUS_APPLY_REFUND]);
                if($res && $add_re){
                    OrderLog::addOrderLog($order_id,$order['uid'],OrderLog::ORDER_LOG_OPERATE_TYPE_USER,'用户申请退款');
                    DB::commit();
                    $res = OrderRefund::orderRefund($order,$lease_id_arr,OrderRefund::ORDER_REFUND_REQUEST_TYPE_XXZ,OrderRefund::ORDER_REFUND_ALLIN);
                    if($res['status']==200){
                        SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_CANCELLED,$order_id);
                        RedisLock::unlock($redis, 'orderIdRefund'.$order_id);
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款成功');
                    }
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款申请已提交至供应商，请等待审核');
                }else{
                    DB::rollBack();
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'退款申请提交失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '待发货订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '待发货订单不存在');
        }
    }

    /**
     * 撤销退款申请
     */
    public function cancelOrderRefund(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $user = $this->member;
            $order = Order::where([['id',$order_id],['uid',$user['id']]])->wherein('status',[OrderService::ORDER_STATUS_APPLY_REFUND,OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_REFUSE])->count();
            $order_refund = OrderRefund::where('order_id',$order_id)->select('id','refund_order_status','order_id')->first();
            $order_refund = obToArray($order_refund);
            if($order > 0 && !empty($order_refund)){
                $refund_res = OrderRefund::where('order_id',$order_id)->update(['refund_status'=>OrderRefund::ORDER_REFUND_CANCEL]);
                $res = Order::where([['id',$order_id],['uid',$user['id']]])->update(['status'=>$order_refund['refund_order_status']]);
                if($res && $refund_res){
                    OrderLog::addOrderLog($order_id,$user['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_USER,'用户撤销退款申请');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款申请已撤销');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'退款申请撤销失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }


    /**
     * 查看物流
     */
    public function checkOrderExpress(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $user = $this->member;
            $order = Order::from('sp_order_2 as o')->where([['o.id',$order_id],['o.uid',$user['id']],['o.status','>=',OrderService::ORDER_STATUS_DELIVER_SUCCESS]])->leftjoin('sp_order_goods_2 as g','g.order_id','o.id')->select('g.goods_title','g.imgurl','g.setmeal_title','o.rent_total','o.month_total','o.amount','o.realname','o.mobile','o.address','o.prov','o.city','o.area','o.begin_time','o.end_time')->first();
            $order = $order ? $order->toArray() : [];
            if($order){
                $order['lease_time'] = date("Y.m.d",strtotime($order['begin_time'])).'-'.date("Y.m.d",strtotime($order['end_time']));
                unset($order['begin_time']);
                unset($order['end_time']);
                $order_return = OrderReturn::where([['order_id',$order_id],['type',OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY]])->select('logistics_name','logistics_no','info','status as express_status','delivery_type')->first();
                $order_return = $order_return ? $order_return->toArray() : [];
                if(!empty($order_return)){
                    if($order_return['delivery_type'] == OrderReturn::ORDER_DELIVERY_TYPE_EXPRESS){
                        if($order_return['express_status'] != OrderReturn::ORDER_EXPRESS_STATUS_SIGNED){
                            //已签收
                            if(!empty($order_return['logistics_no'])){

                                $express_data = LogisticsService::logisticsMessage($order_return['logistics_name'],$order_return['logistics_no'],$order['mobile']);
                                if($express_data){
                                    $order_return['info'] = json_encode($express_data,JSON_UNESCAPED_UNICODE);
                                    OrderReturn::where([['type',OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY],['order_id',$order_id]])
                                        ->update(['info'=>json_encode($express_data,JSON_UNESCAPED_UNICODE)]);
                                }
                            }

                        }else{
                            $order_return['info'] = json_decode($order_return['info'],true);
                        }
                        $order = array_merge($order,$order_return);
                    }
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单未发货');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }


    /**
     * 确认收货
     */
    public function orderConfirmReceiving(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $user = $this->member;
            $order = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_return_2 as r','r.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->where([['o.id',$order_id],['o.uid',$user['id']],['o.status',OrderService::ORDER_STATUS_DELIVER_SUCCESS]])
                ->select('o.id','o.seller_id','o.realname','o.trade_no','o.mobile','r.logistics_name','r.logistics_no','r.status as express_status','r.delivery_type','o.month_total','og.pact_type')->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                    $exdata['status'] = OrderReturn::ORDER_EXPRESS_STATUS_SIGNED;
                    $exdata['confirm_time'] = time();
                    DB::beginTransaction();
                    $ex_res = OrderReturn::where([['type',OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY],['order_id',$order_id]])->update($exdata);
                    $order_data['update_time'] = time();
                    $order_data['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;

                    $order_res = Order::where([['id',$order_id],['uid',$user['id']]])->update($order_data);

                    if($ex_res && $order_res){
                        OrderLog::addOrderLog($order_id,$user['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_USER,'用户确认收货');
                        DB::commit();

                        SendChangeOrderMessage::dispatch($order_id,AlipayMessageService::KX_SHOPPING);

                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'确认收货成功');
                    }else{
                        DB::rollBack();
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '确认收货失败，请联系平台客服处理');
                    }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 获取买断详情
     */
    public function getOrderBuyoutData(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->wherein('o.status',OrderService::getOrderStatus(OrderService::ORDER_BUYOUT_STATUS))
                ->leftjoin('sp_order_goods_2 as g','g.order_id','o.id')
                ->select('o.trade_no','g.goods_title','g.imgurl','g.setmeal_title','o.amount','o.rent_total',
                    'g.setmeal_price','o.begin_time','o.end_time','o.other_order_id','o.other_user_id','g.foregift_price','g.setmeal_foregift')->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                $paid_lease = OrderLease::where([['order_id',$order_id]])->where('paid_rent','>','0')->select('id','paid_rent')->get();
                $paid_lease = $paid_lease ? $paid_lease->toArray() : [];
                if(!empty($paid_lease)){
                    $order['paid_total_rent'] = array_sum(array_column($paid_lease,'paid_rent'));
                    $order['paid_count'] = count($paid_lease);
                }else{
                    $order['paid_total_rent'] = 0;
                    $order['paid_count'] = 0;
                }
                $order['lease_term'] = date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time']));
                if(!empty($order['other_user_id']) && !empty($order['other_user_id'])){

                }else{
                   $order['setmeal_price']=$order['setmeal_price']>0?$order['setmeal_price']:0;
                   $order['buyout_amount'] = sprintf("%.2f",$order['rent_total']-$order['paid_total_rent']+$order['setmeal_price']);
                    //  $order['buyout_amount'] = sprintf("%.2f",$order['foregift_price']+$order['setmeal_price']-$order['paid_total_rent']);
                }
                unset($order['begin_time']);
                unset($order['end_time']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 买断支付
     */
    public function orderBuyoutPay(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->wherein('o.status',OrderService::getOrderStatus(OrderService::ORDER_BUYOUT_STATUS))
                ->leftjoin('sp_order_goods_2 as g','g.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as u','o.seller_id','u.member_id')
                ->select('o.mini_id', 'o.trade_no','o.amount','g.goods_id','g.setmeal_price','g.setmeal_foregift','g.goods_title','u.shopname','o.begin_time','o.end_time',
                    'o.rent_total','o.other_user_id','o.other_order_id','g.foregift_price','g.pact_type')->first();
            $order = $order ? $order->toArray() : [];
            if($order['pact_type']!=1){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单买断信息有误，固定租期才能买断，请联系平台客服处理');
            }
            if(!empty($order)){
                $paid_lease = OrderLease::where([['order_id',$order_id]])->where('paid_rent','>','0')->select('id','paid_rent')->get();
                $paid_lease = $paid_lease ? $paid_lease->toArray() : [];
                if(!empty($paid_lease)){
                    $order['paid_total_rent'] = array_sum(array_column($paid_lease,'paid_rent'));
                    $order['paid_count'] = count($paid_lease);
                }else{
                    $order['paid_total_rent'] = 0;
                    $order['paid_count'] = 0;
                }
                $order['lease_term'] = date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time']));
                if(!empty($order['other_user_id']) && !empty($order['other_user_id'])){

                }else{
                    $order['setmeal_price']=$order['setmeal_price']>0?$order['setmeal_price']:0;
                    $buyout_amount = sprintf("%.2f",$order['rent_total']-$order['paid_total_rent']+$order['setmeal_price']);
                    // $buyout_amount = sprintf("%.2f",$order['foregift_price']+$order['setmeal_price']-$order['paid_total_rent']);
                }
                if ($buyout_amount > 0) {

                    $pay_data['miniId'] = $order['mini_id'];
                    $pay_data['orderNo'] = $order['trade_no'];
                    $pay_data['totalAmount'] = $buyout_amount;
                    $pay_data['subject']  = $order['shopname'].$order['goods_title'].'买断';
                    $pay_data['userAlipayUId'] = $this->member['user_id'];
                    $pay_data['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_BUYOUT;

                    $ali_res = AlipayService::alipayBuyoutPay($pay_data);
                    if($ali_res['status']){
                        $data['trade_no'] = $ali_res['data']['trade_no'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'创建成功',$data);
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败',$ali_res);
                    }
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单买断信息有误，请联系平台客服处理');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }


    /**
     * 交易快照
     */
    public function orderTransSnapshot(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
                ->leftjoin('sp_goods_2 as g','g.id','og.goods_id')
                ->leftjoin('sp_goods_depict_2 as gd','g.id','gd.goods_id')
                ->select('o.id','o.rent_total','o.month_total','o.amount','og.goods_id','og.goods_title','og.convey_type1','og.convey_type2','og.lease_set','og.lease_price','og.setmeal_foregift','o.begin_time','o.end_time','o.create_time','g.new_grade','g.rent_label','g.spread_title','gd.images','gd.goods_content')->first();
            $order = obToArray($order);
            if(!empty($order)){
                if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){
                    $order['lease_price'] = $order['lease_price'].'/月';
                }else{
                    $order['lease_price'] = $order['lease_price'].'/期';
                }
                if(!empty($order['new_grade'])){
                    $order['new_grade'] = GoodsService::GOODS_NEW_GRADE_NAME_LIST[$order['new_grade']];
                }
                $order['create_time'] = date('Y-m-d H:i:s');
                $order['convey_type'] = '寄出'.GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$order['convey_type1']].'/退货'.GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$order['convey_type2']];
                unset($order['convey_type1']);
                unset($order['convey_type2']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 获取订单退货地址
     */
    public function getOrderReturnAddress(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            //查询订单是否存证，租用中，待退货状态可操作退货
            $order = Order::where('id',$order_id)->select('id','status','seller_id')->first();
            $order = obToArray($order);
            if(!empty($order)){
                $member_address = MemberAddress::where([['member_id',$order['seller_id']],['is_delete',MemberAddress::MEMBER_ADDRESS_NOT_DELETE]])->select('realname','mobile','province','city','area','address')->orderBy('isdefault','asc')->first();
                $member_address = obToArray($member_address);
                if(!empty($member_address)){
                    $data['realname'] = $member_address['realname'];
                    $data['mobile'] = $member_address['mobile'];
                    $data['address'] = $member_address['province'].$member_address['city'].$member_address['area'].AddressRemoveRepeat($member_address['province'],$member_address['city'],$member_address['area'],$member_address['address']);
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商家未设置退货地址，请联系商家！');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要退货的订单');
        }
    }

    /**
     * 订单退货添加快递信息
     */
    public function orderReturnAddExpress(Request $request){
        $order_id = $request->input('order_id');
        $logistics_name = $request->input('logistics_name','');
        $logistics_no = $request->input('logistics_no','');
        //$deliver_images = $request->input('deliver_images','');
        if(!empty($order_id) && !empty($logistics_name)){
            $order = Order::where('id',$order_id)->whereIn('status',[OrderService::ORDER_STATUS_TOBE_RETURNED,OrderService::ORDER_STATUS_RETURN_OVERDUE,OrderService::ORDER_STATUS_RETURN_APP_AGREE])->select('id','status')->first();
            $order = obToArray($order);
            if(!empty($order)){
                if(trim($logistics_name) == '上门退货'){
                    $return_data['delivery_type'] = OrderReturn::ORDER_DELIVERY_TYPE_SELF;
                }else{
                    $return_data['delivery_type'] = OrderReturn::ORDER_DELIVERY_TYPE_EXPRESS;
                    if(empty($logistics_no)){
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '快递单号不能为空');
                    }
                }
                $return_data['order_id'] = $order_id;
                $return_data['logistics_name'] = $logistics_name;
                $return_data['logistics_no'] = $logistics_no;
                //$return_data['images'] = $deliver_images;
                $return_data['create_time'] = time();
                $return_data['type'] = OrderReturn::ORDER_EXPRESS_TYPE_RETURN;
                $return_data['status'] = OrderReturn::ORDER_EXPRESS_STATUS_DELIVERED;
                if(OrderReturn::where([['order_id',$order_id],['type',OrderReturn::ORDER_EXPRESS_TYPE_RETURN]])->count() == 0){
                    DB::beginTransaction();
                    $return_res = OrderReturn::insert($return_data);
                    $order_res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_RETURN_DELIVER_SUCCESS]);
                    if($return_res && $order_res){
                        DB::commit();
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退货快递信息添加成功');
                    }else{
                        DB::rollBack();
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败，请稍后再试或联系客服处理');
                    }
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退货快递信息已添加，请勿重复操作');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不支持该操作');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '快递名称、单号、发货照片不能为空');
        }
    }

    /**
     * 获取退货物流公司信息
     */
    public function getReturnExpressList(){
        $express = Express::where('return_express',Express::ORDER_RETURN_EXPRESS_YES)->select('name')->get();
        $express = obToArray($express);
        $add_express = [['name'=>'上门退货']];
        $express = array_merge($add_express,$express);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$express);
    }


    /**
     * 申请提前退货
     */
    public function orderApplyReturn(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            if(Order::where('id',$order_id)->whereIn('status',[OrderService::ORDER_STATUS_CONFIRM_GOODS,OrderService::ORDER_STATUS_OVERDUE,OrderService::ORDER_STATUS_RETURN_APP_REFUSE])->count() > 0){
                $res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_RETURN_APPLICATION,'is_abnormal'=>Order::ORDER_IS_ABNORMAL]);
                if($res){
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'申请成功，请等待商家审核');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败，请稍后再试或联系客服处理');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是租赁中');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 撤销申请提前退货
     */
    public function orderReturnCancel(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            if(Order::where('id',$order_id)->whereIn('status',[OrderService::ORDER_STATUS_RETURN_APPLICATION,OrderService::ORDER_STATUS_RETURN_APP_REFUSE])->count() > 0){
                $res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CONFIRM_GOODS,'is_abnormal'=>Order::ORDER_NOT_ABNORMAL,'check_refuse_reason'=>'']);
                if($res){
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退货申请撤销成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败，请稍后再试或联系客服处理');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不支持该操作');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }

    /**
     * 获取退货物流信息
     */
    public function getReturnExpressData(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            if(Order::where('id',$order_id)->count() > 0){
                $order_return = OrderReturn::where([['order_id',$order_id],['type',OrderReturn::ORDER_EXPRESS_TYPE_RETURN]])->select('logistics_name','logistics_no','info','status as express_status','delivery_type')->first();
                $order_return = $order_return ? $order_return->toArray() : [];
                $mobile = Order::where('id',$order_id)->value('mobile');
                if(!empty($order_return)){
                    if($order_return['delivery_type'] == OrderReturn::ORDER_DELIVERY_TYPE_EXPRESS){
                        if($order_return['express_status'] != OrderReturn::ORDER_EXPRESS_STATUS_SIGNED){ //已签收
                            if(!empty($order_return['logistics_no'])){
                                $express_data = LogisticsService::logisticsMessage($order_return['logistics_name'],$order_return['logistics_no'],$mobile);
                                if(isset($express_data['status']) && isset($express_data['ischeck'])){
                                    if($express_data['status'] == 200 && $express_data['ischeck']){
                                        OrderReturn::where([['type',OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY],['order_id',$order_id]])->update(['info'=>json_encode($express_data)]);
                                        $order_return['info'] = $express_data;
                                    }
                                }
                            }
                        }else{
                            $order_return['info'] = json_decode($order_return['info'],true);
                        }
                    }
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order_return);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 获取续租商品状态
     */
    public function getRenewalGoodsStatus(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $goods = OrderGoods::from('sp_order_goods_2 as og')->leftjoin('sp_order_2 as o','og.order_id','o.id')->leftjoin('sp_goods_2 as g','og.goods_id','g.id')->where('og.order_id',$order_id)->select('g.status','og.goods_id','og.setmeal_id','o.trade_no')->first();
            $goods = obToArray($goods);
            if($goods){
                if(Order::where('parent_order_no',$goods['trade_no'])->whereIn('status',OrderService::getOrderStatus(OrderService::OTHER_ORDER_RENEWAL_STATUS))->count() > 0){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单已续租，请勿重复操作');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$goods);
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }



    /**
     * 联通选号
     */
    public function unicomSelect(Request $request){

        $user = $this->member;

        $data = $request->input();

        //1、是否下单
        // (1)身份证号  (2)未选号  (3)审核通过
        $unicom_order = UnicomOrder::where('certId',$user['cert_no'])
                            ->whereNull('phoneNum')
                            ->whereIn('status',[UnicomOrder::UNICOM_STATUS_TWO,UnicomOrder::UNICOM_STATUS_THREE])
                            ->orderBy('id','desc')
                            ->first();
        $unicom_order = obToArray($unicom_order);

        if($unicom_order){
            //2、京东配送地址覆盖查询
            $input1 = array(
                'postProvinceCode'=>$unicom_order['postProvinceCode'], //收货地址省份编码（6位）
                'postCityCode'=>$unicom_order['postCityCode'], //收货地址地市编码（6位）
                'postDistrictCode'=>$unicom_order['postDistrictCode'], //收货地址区县编码（6位）
                'postAddr'=>$unicom_order['postAddr'] //收货地址详情
            );
            $res1 = UnicomService::unicomCheckAddress($input1);

            //3、风控结果
            $input2 = array(
                'certName'=>$unicom_order['certName'], //入网人身份证姓名
                'certNo'=>$unicom_order['certId'], //入网人身份证号码（身份证中的X要求大写）
                'postNumber'=>$unicom_order['mobile'], //联系电话
                'postProvinceCode'=>$unicom_order['postProvinceCode'], //收货地址省份编码（6位）
                'postCityCode'=>$unicom_order['postCityCode'], //收货地址地市编码（6位）
                'postDistrictCode'=>$unicom_order['postDistrictCode'], //收货地址区县编码（6位）
                'postAddr'=>$unicom_order['postAddr'] //收货地址详情
            );
            $res2 = UnicomService::unicomCheck($input2);

            //4、展示号码
            if($res1['success'] && $res2['rspCode'] == '0000'){
                $update_data = array(
                    'result_2'=>json_encode($res2),
                    'result_3'=>json_encode($res1),
                    'status_2'=>UnicomService::RES_SUCCESS,
                    'status_3'=>UnicomService::RES_SUCCESS,
                    'update_time'=>date('Y-m-d H:i:s')
                );
                //更新状态
                UnicomOrder::where('id',$unicom_order['id'])->update($update_data);

                $input3 = array(
                    'goodsId'=>$unicom_order['goodsId'], //商品id
                    'searchValue'=>$data['searchValue']?$data['searchValue']:"" //需要匹配具体号码
                );
                $res3 = UnicomService::unicomSelect($input3);
                if($res3['rspCode'] == "M0"){
                    $res = array_filter($res3['body']['numArray'],function($arr){
                        if($arr>=2){
                            return $arr;
                        }
                    });
                    $data = [];
                    $data['data'] = array_values($res);
                    $data['goodsId'] = $unicom_order['goodsId'];
                    $data['certId'] = $unicom_order['certId'];
                    $data['certName'] = $unicom_order['certName'];
                    $data['id'] = $unicom_order['id'];
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请换一批后重试');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '不符合开卡条件');
            }

        }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '没有包含联通卡套餐的订单，无法选号');
        }


    }

    /**
     * 联通选号预占号码
     */
    public function unicomChange(Request $request){

        $user = $this->member;

        $data = $request->input();


        //1、选号-预占
        if($data['status'] == UnicomService::RES_SUCCESS){
            //同意协议

            $input = array(
                'certNo'=>$data['certNo'], //身份证号码
                'serialNumber'=>$data['phoneNum'], //待预占的号码
            );

            $res = UnicomService::unicomChange($input);
            if($res['rspCode'] == "0000"){
                $update_data = array(
                    'status'=>UnicomOrder::UNICOM_STATUS_TWO,
                    'result_1'=>json_encode($res),
                    'status_1'=>UnicomService::RES_SUCCESS,
                    'status_4'=>UnicomService::RES_SUCCESS,
                    'phoneNum'=>$data['phoneNum'],
                    'update_time'=>date('Y-m-d H:i:s')
                );
                //更新状态
                UnicomOrder::where('id',$data['id'])->update($update_data);

                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'选号成功',$res['uuid']);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '选号失败，请重新选号');
            }

        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请勾选协议');
        }
    }

    /**
     * 用户协议信息查询-暂时不用接口，使用静态文档
     */
    public function unicomProtocal(Request $request){

        $user = $this->member;

        $data = $request->input();

        //1、用户协议信息查询
        $input = array(
            'certName'=>$data['certName'], //入网人身份证姓名
            'certId'=>$data['certId'], //入网人身份证号码（身份证中的X要求大写）
            'phoneNum'=>$data['phoneNum'], //选占号码
            'goodsId'=>$data['goodsId'], //商品id
        );
        $res = UnicomService::unicomProtocal($input);
        if($res['rspCode'] == "0000"){

            $update_data = array(
                'result_4'=>json_encode($res),
                'update_time'=>date('Y-m-d H:i:s')
            );
            //更新状态
            UnicomOrder::where('id',$data['id'])->update($update_data);

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res['body']);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '协议获取失败，请重新选号');
        }

    }

    //查询租赁订单，发起获取签署代扣
    public function createWithholdSign(Request $request){
        $order_id = $request->input('order_id');
        if($order_id) {
            $order = Order::where('id', $order_id)->select('id', 'trade_no','withhold_status', 'sign_status', 'uid', 'status')->first();
            $order=obToArray($order);

            if($order['sign_status']!=2){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同未签署');
            }
            if($order['withhold_status']){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已签约');
            }
            $res= AntchainAtoService::CreateWithholdSign($order['trade_no']);

            if($res['resultCode']=='OK'){
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',['signStr'=>$res['signStr'],'orderId'=>$order['trade_no']]);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['resultMsg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }


    /**
     * 获取公证链接
     */
    public function getNotaryUrl(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order= Order::where('id',$order_id)->select('contract_id','is_notary','notary_url')->first();
            $contract_id=$order['contract_id'];
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
//        if(!$contract_id){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '公证信息不存在');
//        }
        $is_notary=$order['is_notary'];;
        if($is_notary){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'已协议公证成功');
        }
        if($is_notary){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'已协议公证成功');
        }
        $res=NotarizeService::notaryQuery($contract_id);
        if($res['state']=='3'){
            $data=$res['data'];
            foreach ($data as $k=>$v){
                $fileUrl=$v['fileURL'];
                $fileName = rand(10,99).$k.$contract_id.".pdf";
                $file = file_get_contents($fileUrl);
                $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

                file_put_contents($path,$file);
                $uploud_res = AlipayService::upload($fileName,$path);
                if($uploud_res['status']){
                    if(file_exists($path)){
                        unlink($path);
                    }
                }
                $data[$k]['dlzpdfurl']=$fileName;
            }
            Order::where('contract_id',$contract_id)->limit(1)->update(['is_notary'=>1,'notary_info'=>json_encode($data)]);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, $res['msg'],$res);
        }

        $res=NotarizeService::notaryReady($contract_id);
        if($res['status']==204){
            $res=NotarizeService::get_notary_link($contract_id);
        }

        if($res['status']!=200){
            $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->leftjoin('sp_order_credit as c','c.order_id','o.id')
                ->leftjoin('sp_member_2 as u','o.uid','u.id')
                ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
                ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
                ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
                ->select(
                    'o.id','o.trade_no','o.begin_time','o.zulinbao_order_id','o.end_time','o.pact_url_3','o.uid','o.seller_id','o.is_insurance_choose',
                    'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
                    'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
                    ,'c.platformLoanNo','o.create_time'
                    ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
                    ,'u.idcard_front','u.idcard_back','og.id as order_goods_id ','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title',
                    'og.lease_set','og.setmeal_price','og.setmeal_foregift','o.prepayment_total','o.pact_url',
                    'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
                    ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
                    ,'su.ant_user_id as mer_ant_id','o.sign_no','su.esign_seal_id','su.ant_seal_id'
                    ,'g.new_grade')
                ->first();
            $order = $order ? $order->toArray() : [];
            NotarizeService::uploadOrderInfo($order);
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);

    }

    /**
     * 生成线下店铺订单
     */
    public function makeLineOrder(Request $request){
        $data = $request->input();
        $user = $this->member;
        $data['status']=OrderService::ORDER_STATUS_NOT_PAY;
        $res = Order::createLineOrder($data,$user);
        if($res['status'] == CommonService::HTTP_CODE_SUCCESS){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'订单创建成功',$res['data']);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }
    }


    //创建信用购订单
    public function creditBizOrderCreate(Request $request){
        $order = Order::where('id', '11778')
            ->select('id', 'mini_id', 'trade_no', 'rent_total', 'rights_auth_no', 'foregift', 'month_total',
                'amount', 'uid', 'status', 'address', 'mobile', 'realname')
            ->first();
        $order = $order ? $order->toArray() : [];

        $order_goods = OrderGoods::from('sp_order_goods_2 as og')->select('og.goods_title','og.id', 'og.setmeal_foregift', 'og.pact_type', 'c.rent_category')
            ->leftjoin('sp_goods_2 as g', 'g.id', 'og.goods_id')
            ->leftjoin('sp_category as c', 'c.id', 'g.category_id')
            ->where('og.order_id', '10419')
            ->first();
        $order_goods = $order_goods ? $order_goods->toArray() : [];

        $data['mini_id'] = $order['mini_id'];
        $data['userAlipayUId'] = $this->member['user_id'];
        $data['rentPeriod'] = $order['month_total'] * 30;
        $data['rentAmount'] = $order['rent_total'];
        $data['orderNo'] = $order['trade_no'];
        $data['goodsTitle'] = $order_goods['goods_title'];
        $data['goodsId'] = $order_goods['id'];

        $data['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_XXZ_URL_PAY;
        $ali_res = AlipayService::creditbizorderCreatePay($order['mini_id'], $data);
        if ($ali_res['status']) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '创建成功', $ali_res['data']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $ali_res['message']);
        }
    }
}
